
const db = require("../db/index")
const jwt = require("jsonwebtoken")
const {secretKey,expiresIn} = require("../config/index")
const {formatDateTime} = require("../tools/dateFormat")

//获取用户信息
exports.getNNUserInfo = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const sql = "SELECT * FROM nn_user WHERE uid = ?"
        db.query(sql,data.userId,(err,results) => {
            if (err) {
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            res.send({
                status:200,
                message:"获取用户信息成功",
                data:results[0]
            })
        })
        
    })
}

// 修改用户名
exports.editNNUserName = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const sql = "UPDATE nn_user set name=? WHERE uid=?"
        //如果有多个参数，query的第二个入参是数组
        db.query(sql,[userInfo.name,data.userId],(err,results) => {
            if (err) {
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            // const updateSql = "UPDATE user set name=? WHERE userId=?"
            // db.query(updateSql,userInfo.name,)
            res.send({
                status:200,
                message:"修改用户信息成功",
                // data:results
            })
        })
        
    })
}

// 修改头像
exports.editNNUserImage = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const sql = "UPDATE nn_user set image=? WHERE uid=?"
        //如果有多个参数，query的第二个入参是数组
        console.log(userInfo,'userInfo')
        db.query(sql,[userInfo.image,data.userId],(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            // const updateSql = "UPDATE user set name=? WHERE userId=?"
            // db.query(updateSql,userInfo.name,)
            res.send({
                status:200,
                message:"修改用户信息成功",
                // data:results
            })
        })
        
    })
}

// 修改定位信息
exports.editUserLocation = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const sql = "UPDATE user set lat=?,lng=? WHERE userId=?"
        //如果有多个参数，query的第二个入参是数组
        console.log(userInfo,'userInfo')
        db.query(sql,[userInfo.lat,userInfo.lng,data.userId],(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            // const updateSql = "UPDATE user set name=? WHERE userId=?"
            // db.query(updateSql,userInfo.name,)
            res.send({
                status:200,
                message:"修改用户信息成功",
                // data:results
            })
        })
        
    })
}

//根据经纬度获取周边用户信息列表
exports.getUserList = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    // console.log(userInfo,'根据经纬度获取周边用户信息列表')
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(userInfo,'userInfo')
        console.log(data,'jwt解析')
        let maxLng = parseFloat(userInfo.lng) + 0.5
        let minLng = parseFloat(userInfo.lng) - 0.5
        let maxLat = parseFloat(userInfo.lat) + 0.5
        let minLat = parseFloat(userInfo.lat) - 0.5
        console.log(minLng,maxLng,minLat,maxLat,'经纬度')
        const sql = "SELECT * from user WHERE lng > ? and lng < ? and lat > ? and lat < ? and userId != ?"
        db.query(sql,[minLng,maxLng,minLat,maxLat,data.userId],(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            // const updateSql = "UPDATE user set name=? WHERE userId=?"
            // db.query(updateSql,userInfo.name,)
            res.send({
                status:200,
                message:"修改用户信息成功",
                data:results
            })
        })
        
    })
}


// 上传用户使用记录
exports.upDateUserHistory = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const sql = "INSERT INTO history (name, price, oil, dateString, modelId, userId) VALUES (?,?,?,?,?,?)"
        //如果有多个参数，query的第二个入参是数组
        console.log(userInfo,'上传用户使用记录info')
        db.query(sql,[
            userInfo.name,
            userInfo.price,
            userInfo.oil,
            userInfo.dateString,
            userInfo.modelId,
            data.userId],(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            // const updateSql = "UPDATE user set name=? WHERE userId=?"
            // db.query(updateSql,userInfo.name,)
            res.send({
                status:200,
                message:"修改用户信息成功",
                // data:results
            })
        })
        
    })
}

//获取用户使用列表
exports.getUserUesHistory = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    // console.log(userInfo,'根据经纬度获取周边用户信息列表')
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(userInfo,'userInfo')
        
        //创建date变量
        var nowDate = new Date();
        var min = new Date(nowDate.setDate(nowDate.getDate() - 100))
        let maxDate = formatDateTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
        let minDate = formatDateTime(min, 'yyyy-MM-dd HH:mm:ss')
        console.log("maxDate",maxDate,minDate)
        const sql = "SELECT * from history WHERE dateString > ? and dateString < ? and userId = ? order by dateString desc"

        db.query(sql,[
            minDate,
            maxDate,
            userInfo.userId],(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            // const updateSql = "UPDATE user set name=? WHERE userId=?"
            // db.query(updateSql,userInfo.name,)
            res.send({
                status:200,
                message:"获取用户使用记录成功",
                data:results
            })
        })
        
    })
}

//根据userId获取对应用户信息
exports.getUserInfoByUserId = (req,res) => {
    console.log('req',req.body)
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(data,'jwt解析')
        const userId = req.body.userId || ""
        console.log(userId,'userId')
        const sql = "SELECT * FROM user WHERE userId = ?"
        db.query(sql,userId,(err,results) => {
            if (err) {
                return res.send({ status: 500, message: "未找到用户" });
            }
            console.log(results,'sql results')
            res.send({
                status:200,
                message:"获取用户信息成功",
                data:results
            })
        })
        
    })
}

//插入用户使用记录
exports.setNNUserHistory = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    // console.log(userInfo,'根据经纬度获取周边用户信息列表')
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(userInfo,'userInfo')
        const userId = req.body.userId || ""
        console.log(data,'data')

        let insertData = {
            uid:data.userId,
            createTime:formatDateTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
            count:userInfo.count,
            // calorie:"0",
            // startTime:"",
            // endTime:"",
            remark:userInfo.remark,
            other:userInfo.other,
            duration:userInfo.duration,
            isWatch:userInfo.isWatch,
            heartRate:userInfo.heartRate,
           }
           console.log("用户插入数据",insertData)
           const sqlSocial = "INSERT INTO nn_history SET ?";
           db.query(sqlSocial,insertData,(err,results) => {
                if (err) {
                    console.log(err,'err')
                    return res.send({ status: 500, message: "插入数据失败" });
                }
                res.send({
                    status:200,
                    message:"存储用户使用记录成功"
                })
           })
    })
}


//获取用户使用记录
exports.getNNHistory = (req,res) => {
    console.log(req.headers.authorization.slice(7),'req')
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(userInfo,'userInfo')
        console.log(data,'data')
        const {startDate,endDate} = userInfo
        var sql = ""
        var sqlArr = []
        if (startDate == null || startDate.length == 0 || endDate == null || endDate.length == 0) {
            sql = "SELECT * from nn_history WHERE uid = ?"
            sqlArr = [data.userId]
        } else {
            sql = "SELECT * from nn_history WHERE uid = ? and createTime > ? and createTime < ? ORDER BY createTime    ASC"
            sqlArr = [data.userId,startDate,endDate]
        }
        db.query(sql,sqlArr,(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "插入数据失败" });
            }
            res.send({
                status:200,
                message:"获取用户使用记录成功",
                data:results
            })
       })
    })
}

//根据日期获取用户使用记录
exports.getNNHistoryWithDate = (req,res) => {
    const token = req.headers.authorization.slice(7)
    const userInfo = req.body
    if (token == null){
        res.send({
            status:500,
            message:"token错误"
        })
        return
    }
    jwt.verify(token,secretKey,(err,data) => {
        if(err) {
            res.send({
                status:500,
                message:"token解析失败"
            })
            return
        }
        console.log(userInfo,'userInfo')
        console.log(data,'data')
        const {startDate,endDate} = userInfo
        var sql = ""
        var sqlArr = []
        
        sql = "SELECT * from nn_history WHERE uid = ? and createTime > ? and createTime < ? ORDER BY createTime    ASC"
        sqlArr = [data.userId,startDate,endDate]
        
        db.query(sql,sqlArr,(err,results) => {
            if (err) {
                console.log(err,'err')
                return res.send({ status: 500, message: "插入数据失败" });
            }
            if (results.length > 0) {
                res.send({
                    status:200,
                    message:"获取用户使用记录成功",
                    data:results[0]
                })
            } else {
                res.send({
                    status:200,
                    message:"获取用户使用记录成功",
                    data:{
                        createTime:"",
                        count:"0",
                        // calorie:"0",
                        uid:"",
                        remark:"",
                        other:"",
                        duration:"0",
                        id:0,
                        heartRate:"0",
                        isWatch:"0",
                    }
                })
            }
            
       })
    })
}
